package threadcoreknowledge.sixstates;

import org.omg.PortableInterceptor.INACTIVE;

/**
 * @ClassName BlockedWaitingTimedWaiting
 * @Description TODO 展示Blocked，Waiting，TimedWaiting
 * @Author wushaopei
 * @Date 2021/4/19 6:33
 * @Version 1.0
 */
public class BlockedWaitingTimedWaiting implements Runnable{

    public static void main(String[] args) {
        BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
        Thread thread1 = new Thread(runnable);
        thread1.start();
        Thread thread2 = new Thread(runnable);
        thread2.start();
        // 主线程休眠 5ms ，避免执行太快看不到thread1的 TIMED_WAITING状态
        try {
            Thread.sleep(5);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        // 打印出Timed_Waiting状态，因为正在执行 Thread.sleep(1000)
        System.out.println(thread1.getState());
        // 打印出 BLOCKED 状态，因为thread2想拿到syn()的锁却拿不到
        System.out.println(thread2.getState());

        // waiting
        try {
            Thread.sleep(1300);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        // 打印出WAITING状态，因为执行了wait()
        System.out.println(thread1.getState());
    }

    @Override
    public void run() {
        syn();
    }

    /**
     * @Description TODO 同步等待
     */
    private synchronized void syn(){
        try {
            // sleep 1s ,此时锁被线程1持有，而线程2进来拿不到锁进入等待状态
            Thread.sleep(1000);
            wait();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}
